package com.coollang.smartbra.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coollang.smartbra.MyAutoLayoutActivity;
import com.coollang.smartbra.R;
import com.coollang.smartbra.base.FragmentFactory;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.beans.VersionBean;
import com.coollang.smartbra.bleutil.BleUtil;
import com.coollang.smartbra.bleutil.callback.BleCallbackImpl;
import com.coollang.smartbra.eventbus.CommonEvent;
import com.coollang.smartbra.fragment.DrawerLayoutFragment;
import com.coollang.smartbra.fragment.EnFragment;
import com.coollang.smartbra.fragment.FirstFragment;
import com.coollang.smartbra.presenter.MainActivityPresenter;
import com.coollang.smartbra.utils.PreferencesUtils;
import com.coollang.smartbra.utils.StringUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.TranslucentSystemBarUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.umeng.socialize.UMShareAPI;

import de.greenrobot.event.EventBus;


/**
 * @author Timmy
 *         说明:主界面
 */
public class MainActivity extends MyAutoLayoutActivity implements RadioGroup.OnCheckedChangeListener {

    /**
     * 底部菜单
     */
    private RadioGroup main_menu;
    private String curFragment;
    private FragmentManager fragmentManager;
    private TextView mTvNews;
    private DrawerLayoutFragment mDrawerLayoutFragment;
    private RadioButton menu_en;
    private MainActivityPresenter mPresenter;

    private int mStemp = 0;
    /**
     * 返回两次退出
     */
    private boolean firstBack = true;

    public DrawerLayout mDrawerLayout;
    /**
     * 首页菜单
     */
    public RadioButton menu_frist;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        findViewByIds();
        initListener();
        initFragment();
        menu_frist.setChecked(true);

        mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                // mDrawerLayoutFragment.mOptionCircle.stopAnimation();
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                mDrawerLayoutFragment.setBleinfo();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        bleListener();
        // 同步步数
        // BleUtil.getInstance().sendData((byte) 0x30);
        // 获取今日数据
        // mPresenter.getOneActionToday();
    }

    @Override
    protected void onStop() {
        super.onStop();
        setEnFragmengBleCommand(2);
    }

    private void bleListener() {
        // 开启通知检测
        if (MyApplication.getApplication().isConnected) {
            BleUtil.getInstance().registerNotifyListener(mBleNotifyListener);
        }
    }

    /**
     * 首页面不需要做停止检测,避免熄灭屏幕的时候收不到数据的情况
     */
    private void bleUnListener() {
        // 开启通知检测
        if (MyApplication.getApplication().isConnected) {
            BleUtil.getInstance().unRegisterNotifyListener();
        }
    }

    private BleCallbackImpl mBleNotifyListener = new BleCallbackImpl() {
        @Override
        public void onBleDisconnected() {
            // 蓝牙断开
        }

        @Override
        public void onVOCMeasureStart(byte b) {
            getEnFragment().onVOCMeasureStart(b);
        }

        @Override
        protected void onEnMeasureDataRecieved(int tempState, int temp, int shidu, int ziwaixian) {
            getEnFragment().onEnMeasureDataRecieved(tempState, temp, shidu, ziwaixian);
        }

        @Override
        public void onVOCMeasureData(int jiaquan, int tvoc, int co2) {
            getEnFragment().onVOCMeasureData(jiaquan, tvoc, co2);
        }

        @Override
        protected void onStepsRecieved(byte[] data, int dates, long sportTimes, int steps) {
            // 步数
            mStemp = steps;
            /**
             *
             * 这里将步数数据存储起来
             *
             * 先进行查询, 如果没有就存储
             */
            mPresenter.updateStepsData(mStemp);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return goBack(keyCode, event);
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private Handler mHandler = new Handler();

    private boolean goBack(int keyCode, KeyEvent event) {
        if (firstBack) {
            ToastUtils.showToast(getString(R.string.go_to_exit));
            firstBack = false;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    firstBack = true;
                }
            }, 2000);
            return true;
        } else {
            mHandler.removeCallbacksAndMessages(null);
            MyApplication.isActive = false;
            MyApplication.getApplication().disConnectDevice();
            firstBack = true;
            finishActivity();
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BleUtil.getInstance().disconnect();
        EventBus.getDefault().unregister(this);
        UMShareAPI.get(this).release();
    }

    public void onEventMainThread(CommonEvent event) {
        if (event.type == CommonEvent.GETLASTVERSION) {
            switch (event.what) {
                case CommonEvent.REQUESTSUEECCD:
                    VersionBean versionBean = (VersionBean) StringUtils.parseJSonSafe(event.msg, new VersionBean());
                    String getVersion = versionBean.getData().getVersion();
                    if (!checkVersion(MyApplication.getApplication().version, getVersion)) {
                        //不用升级，已是最新版本
                        mTvNews.setVisibility(View.GONE);
                        PreferencesUtils.putBoolean(this, "hasNewVersion", false);
                    } else {
                        //要升级
                        mTvNews.setVisibility(View.VISIBLE);
                        PreferencesUtils.putBoolean(this, "hasNewVersion", true);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 需要升级返回true
     */
    private boolean checkVersion(String deviceVersion, String webVersion) {
        deviceVersion = deviceVersion.toLowerCase();
        webVersion = webVersion.toLowerCase();

        if (deviceVersion.startsWith("v")) {
            deviceVersion = deviceVersion.substring(1);
        }

        if (webVersion.startsWith("v")) {
            webVersion = webVersion.substring(1);
        }

        String[] device = deviceVersion.split("\\.");
        String[] web = webVersion.split("\\.");

        Integer[] intDevice = new Integer[device.length];
        for (int i = 0; i < device.length; i++) {
            intDevice[i] = Integer.parseInt(device[i]);
        }

        Integer[] intWeb = new Integer[web.length];
        for (int i = 0; i < web.length; i++) {
            intWeb[i] = Integer.parseInt(web[i]);
        }

        int min = Math.min(device.length, web.length);
        for (int i = 0; i < min; i++) {
            if (intDevice[i] < intWeb[i]) {
                return true;
            }
        }
        return false;
    }

    public void setDrawerLayoutFragment(DrawerLayoutFragment drawerLayoutFragment) {
        mDrawerLayoutFragment = drawerLayoutFragment;
    }

    private void initListener() {
        main_menu.setOnCheckedChangeListener(this);
    }

    private void findViewByIds() {
        main_menu = (RadioGroup) findViewById(R.id.menu_radio);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawer_layout);
        mTvNews = (TextView) findViewById(R.id.tv_news);

        menu_frist = (RadioButton) findViewById(R.id.rb_frist);
        menu_en = (RadioButton) findViewById(R.id.rb_en);
        RelativeLayout content = (RelativeLayout) findViewById(R.id.content);
        // 沉浸式状态栏
        TranslucentSystemBarUtils.showChenJinZhuangTaiLan(this, content);
    }

    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        transaction.
                add(R.id.fl_content_main,
                        FragmentFactory.createFragment(FragmentFactory.TAB_FIRST),
                        String.valueOf(FragmentFactory.TAB_FIRST))
                .commit();

        curFragment = String.valueOf(FragmentFactory.TAB_FIRST);
    }

    @Override
    protected void initData() {

        mPresenter = new MainActivityPresenter(this);
        mPresenter.getDeviceList();
        mPresenter.getUserGola();
        mPresenter.getUserInfo();
    }

    private boolean isEnFragment;

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        if (!firstBack) {
            firstBack = true;
        }

        if (isEnFragment) {
            // 如果是在enFragmeng
            if (getEnFragment().timeIsStart) {
                // 说明正在测量温湿度
                // 弹窗
                menu_en.setChecked(true);
                // 弹窗
                // 请求是否
                showEnfragmengDialog(checkedId);
                return;
            }
        }

        // 默认不是在enFragment
        isEnFragment = false;

        // 设置小红点
        boolean hasNewVersion = PreferencesUtils.getBoolean(UIUtils.getContext(), "hasNewVersion");
        if (hasNewVersion && MyApplication.getApplication().isConnected) {
            mTvNews.setVisibility(View.VISIBLE);
        } else {
            mTvNews.setVisibility(View.GONE);
        }

        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        switch (checkedId) {
            case R.id.rb_frist:
                // 设置侧滑栏可以拉出
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                setGoBack(String.valueOf(FragmentFactory.TAB_FIRST));

                switchContent(curFragment,
                        FragmentFactory
                                .createFragment(FragmentFactory.TAB_FIRST), String.valueOf(FragmentFactory.TAB_FIRST));
                break;
            case R.id.rb_sport:
                // 设置侧滑栏不能拉出
                setGoBack(String.valueOf(FragmentFactory.TAB_SPORT));
                switchContent(curFragment, FragmentFactory.createFragment(FragmentFactory.TAB_SPORT), String.valueOf(FragmentFactory.TAB_SPORT));
                break;
            case R.id.rb_en:
                setGoBack(String.valueOf(FragmentFactory.TAB_EN));
                switchContent(curFragment, FragmentFactory.createFragment(FragmentFactory.TAB_EN), String.valueOf(FragmentFactory.TAB_EN));

                isEnFragment = true;
                break;
            case R.id.rb_person:
                // 设置小红点隐藏
                mTvNews.setVisibility(View.INVISIBLE);
                setGoBack(String.valueOf(FragmentFactory.TAB_PERSONAL));
                switchContent(curFragment, FragmentFactory.createFragment(FragmentFactory.TAB_PERSONAL), String.valueOf(FragmentFactory.TAB_PERSONAL));
                break;
            default:
                break;
        }
    }

    private AlertDialog mAlertDialog;

    private void showEnfragmengDialog(final int checkedId) {

        if (mAlertDialog == null) {
            mAlertDialog = new AlertDialog.Builder(this).create();
        }
        mAlertDialog.setMessage("当前正在测量,是否退出测量?");
        mAlertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel1), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 点击事件的回调方法
                dialog.dismiss();

            }
        });

        mAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getEnFragment().dropOutMeasuring();
                main_menu.check(checkedId);
            }
        });
        mAlertDialog.setCanceledOnTouchOutside(false);

        if (!mAlertDialog.isShowing()) {
            mAlertDialog.show();
        }

        Button posiviveButton = mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        posiviveButton.setTextColor(Color.parseColor("#F79444"));
        Button negativeButton = mAlertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(Color.parseColor("#000000"));
    }

    /**
     * 设置环境页面数据
     */
    public void setEnFragmengBleCommand(int command) {
        switch (command) {
            // 开启读取温湿度检测
            case 1:
                BleUtil.getInstance().sendData((byte) 0x41);
                break;
            // 关闭温湿度检测
            case 2:
                BleUtil.getInstance().sendData((byte) 0x41, (byte) 0x02);
                break;
            // 检测voc二氧化碳等...
            case 3:
                BleUtil.getInstance().sendData((byte) 0x43);
                break;
            // 停止检测voc 二氧化碳..
            case 4:
                BleUtil.getInstance().sendData((byte) 0x43, (byte) 0x02);
                break;
            default:
                break;
        }
    }

    private void setGoBack(String anObject) {
        if (curFragment.equals(anObject)) {
            if (!firstBack) {
                firstBack = false;
            }
        }
    }

    /**
     * Fragment切换
     */
    private void switchContent(String from, Fragment to, String tag) {

        if (!curFragment.equals(tag)) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            Fragment findFragmentByTag = fragmentManager.findFragmentByTag(from);
            curFragment = tag;
            /**
             * 先判断是否被add过
             */
            if (!to.isAdded()) {
                transaction.
                        hide(findFragmentByTag)
                        .add(R.id.fl_content_main, to, tag)
                        .commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction
                        .hide(findFragmentByTag)
                        .show(to)
                        .commit(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    /**
     * 获取环境页面
     */
    public EnFragment getEnFragment() {
        return (EnFragment) FragmentFactory.createFragment(FragmentFactory.TAB_EN);
    }

    /**
     * 获取首页面
     */
    public FirstFragment getFirstFragment() {
        return (FirstFragment) FragmentFactory.createFragment(FragmentFactory.TAB_FIRST);
    }

    /**
     * 查询平板支撑数据
     */
    public int queryPbzcActionData() {
        return mPresenter.queryPbzcActionData();
    }

    /**
     * 步数
     */
    public int queryStempActionData() {
        return mStemp;
    }

    /**
     * 查询对应的运动个数
     */
    public int queryCountActionData(int pressedOffset) {
        return mPresenter.queryCountActionData(pressedOffset);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
